package com.atguigu.gmall.product.service;

import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: 李旭
 * @create: 2021-09-28 14:27
 **/
@Service
public class ManageServiceImpl implements ManageService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;
    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;
    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;
    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;
    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;
    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;
    @Autowired
    private SpuInfoMapper spuInfoMapper;

    //获取一级分类的集合
    @Override
    public List<BaseCategory1> getCategory1() {
        return baseCategory1Mapper.selectList(null);
    }

    //获取 二级分类的集合/
    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        return baseCategory2Mapper.selectList(new QueryWrapper<BaseCategory2>()
                .eq("category1_id", category1Id));
    }

    //获取三级分类的集合
    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        return baseCategory3Mapper.selectList(new QueryWrapper<BaseCategory3>()
                .eq("category2_id", category2Id));
    }

    //根据分类id获取平台属性
    @Override
    public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        return baseAttrInfoMapper.attrInfoList(category1Id, category2Id, category3Id);
    }

    //添加平台属性
    @Override
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {

        //1:平台属性表  1
        baseAttrInfoMapper.insert(baseAttrInfo);//主键返回来了
        //2：平台属性值表 多
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        if (!CollectionUtils.isEmpty(attrValueList)) {
            attrValueList.forEach(attrValue -> {
                //外键
                attrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueMapper.insert(attrValue);
            });
        }
    }

    //查询品牌的分页
    @Override
    public IPage baseTrademark(Integer page, Integer limit) {
        return baseTrademarkMapper.selectPage(new Page<BaseTrademark>(page, limit), null);
    }

    //查询商品分页 根据三级分类ID
    @Override
    public IPage spuPage(Integer page, Integer limit, Long category3Id) {
        return spuInfoMapper.selectPage(new Page<SpuInfo>(page, limit),
                new QueryWrapper<SpuInfo>().eq("category3_id", category3Id));
    }

    @Override
    public List<BaseTrademark> getTrademarkList() {
        return baseTrademarkMapper.selectList(null);
    }

    @Override
    public List<BaseSaleAttr> baseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }

    //保存SPU
    @Override
    public void saveSpuInfo(SpuInfo spuInfo) {
        //1:spu_info
        spuInfoMapper.insert(spuInfo); //返回值 主键
        //2:spu_image
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        spuImageList.forEach(spuImage -> {
            spuImage.setSpuId(spuInfo.getId());
            spuImageMapper.insert(spuImage);
        });
        //3.spu_sale_attr
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        spuSaleAttrList.forEach(spuSaleAttr -> {
            spuSaleAttr.setSpuId(spuInfo.getId());
            spuSaleAttrMapper.insert(spuSaleAttr);

            //4:spu_sale_attr_value
            List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
            spuSaleAttrValueList.forEach(spuSaleAttrValue -> {
                spuSaleAttrValue.setSpuId(spuInfo.getId());
                spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                spuSaleAttrValueMapper.insert(spuSaleAttrValue);
            });
        });

    }

    //为了添加SKU 查询spuId对应的所有图片
    @Override
    public List<SpuImage> spuImageList(Long spuId) {
        return spuImageMapper.selectList(new QueryWrapper<SpuImage>()
                .eq("spu_id", spuId));
    }

    //为了添加SKU  查询spuId 对应的销售属性及属性值集合
    @Override
    public List<SpuSaleAttr> spuSaleAttrList(Long spuId) {
        return spuSaleAttrMapper.spuSaleAttrList(spuId);
    }

    //保存SKU
    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {
        //1:sku_info
        skuInfoMapper.insert(skuInfo);
        //2:sku_image
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        skuImageList.forEach(skuImage -> {
            skuImage.setSkuId(skuInfo.getId());
            skuImageMapper.insert(skuImage);
        });
        //3:sku_attr_value
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        skuAttrValueList.forEach(skuAttrValue -> {
            skuAttrValue.setSkuId(skuInfo.getId());
            skuAttrValueMapper.insert(skuAttrValue);
        });
        //4:sku_sale_attr
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        skuSaleAttrValueList.forEach(skuSaleAttrValue -> {
            skuSaleAttrValue.setSkuId(skuInfo.getId());
            //spu_id
            skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
            skuSaleAttrValueMapper.insert(skuSaleAttrValue);
        });
    }

    @Override
    public IPage skuPage(Integer page, Integer limit) {
        return skuInfoMapper.selectPage(new Page<SkuInfo>(page, limit), null);
    }

    //上架
    @Override
    public void onSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.ONSALE);//硬编码问题  1：常量类 （不成立） 公共的所有项目都使用
        skuInfoMapper.updateById(skuInfo); // update sku_info set is_sale = ? where id = ?
        //发消息给MQ  添加索引库
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,
                MqConst.ROUTING_GOODS_UPPER,skuId);
    }

    //下架
    @Override
    public void cancelSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.NOSALE);//硬编码问题   ON
        skuInfoMapper.updateById(skuInfo); // update sku_info set is_sale = ? where id = ?
        //发消息给MQ  删除索引库
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,
                MqConst.ROUTING_GOODS_LOWER,skuId);
    }

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private RedissonClient redissonClient;//Redis儿子的使用方式
    @Override //分布式锁解决缓存击穿问题  使用Redisson
    public SkuInfo getSkuInfo(Long skuId) {
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;//RedisKey的规范
        String cacheKeyLock = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;//RedisKey的规范
        //1:先查询缓存
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        if (null == skuInfo) {
            RLock lock = redissonClient.getLock(cacheKeyLock);//cacheKeyLock : 锁的名称
            //参数1：尝试多久  获取锁
            //参数2：  获取锁持有时间  (死锁）
            try {
                boolean isLock = lock.tryLock(RedisConst.SKULOCK_EXPIRE_PX1,
                        RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
                if(isLock){
                    // 查询DB
                    try {
                        skuInfo = skuInfoMapper.selectById(skuId);
                        if (null != skuInfo) {
                            //查询图片
                            skuInfo.setSkuImageList(skuImageMapper.selectList(new QueryWrapper<SkuImage>()
                                    .eq("sku_id", skuId)));
                            //4:保存缓存一份
                            redisTemplate.opsForValue().set(cacheKey,skuInfo,//缓存雪崩
                                    RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300)
                                    , TimeUnit.SECONDS);
                        }else{
                            //缓存的第一大问题 缓存穿透
                            skuInfo = new SkuInfo();//空结果  空对象
                            redisTemplate.opsForValue().set(cacheKey,skuInfo,5, TimeUnit.MINUTES);
                        }
                    } finally {
                        //解锁
                        lock.unlock();
                    }
                }else{
                    //没有上锁
                    TimeUnit.SECONDS.sleep(2);
                    return (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return skuInfo;
    }

   /* @Override //分布式锁解决缓存击穿问题
    public SkuInfo getSkuInfo(Long skuId) {
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;//RedisKey的规范
        String cacheKeyLock = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;//RedisKey的规范
        //1:先查询缓存
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        if (null == skuInfo) {
            //3:没有  上锁 (分布式锁） 过期不候
            String uuid = UUID.randomUUID().toString();
            Boolean isLock = redisTemplate.opsForValue().setIfAbsent(cacheKeyLock, uuid,
                    RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
            if(isLock){
                //获取到了分布式锁
                // 查询DB
                try {
                    skuInfo = skuInfoMapper.selectById(skuId);
                    if (null != skuInfo) {
                        //查询图片
                        skuInfo.setSkuImageList(skuImageMapper.selectList(new QueryWrapper<SkuImage>()
                                .eq("sku_id", skuId)));
                        //4:保存缓存一份
                        redisTemplate.opsForValue().set(cacheKey,skuInfo,//缓存雪崩
                                RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300)
                                , TimeUnit.SECONDS);
                    }else{
                        //缓存的第一大问题 缓存穿透
                        skuInfo = new SkuInfo();//空结果  空对象
                        redisTemplate.opsForValue().set(cacheKey,skuInfo,5, TimeUnit.MINUTES);
                    }
                } finally {
                    //解锁
                    String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return tostring(redis.call('del',KEYS[1])) else return 0 end";
                    this.redisTemplate.execute(new DefaultRedisScript<>(script),
                            Collections.singletonList(cacheKeyLock), uuid);
                }
            }else{
                //未获取到锁
                try {
                    TimeUnit.SECONDS.sleep(3);
                    return (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        //5:再返回
        return skuInfo;
    }*/
    //根据skuID  查询库存表  sku_info  通过主键  https://item.jd.com/10002133333333333830456.html
    private final Lock lock = new ReentrantLock();// 公平锁：等待时间越长 越优先拿到锁
   /* @Override  本地锁方式解决缓存击穿问题
    public SkuInfo getSkuInfo(Long skuId) {
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;//RedisKey的规范
        //1:先查询缓存
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        if (null == skuInfo) {
            //3:没有  上锁 （本地锁）   过期不候的锁  不能上不见不散的锁
            try {
                //如果在1S内获取锁成功 返回值 true 失败了 返回值false
                boolean tryLock = lock.tryLock(1, TimeUnit.SECONDS);
                if(tryLock){
                    //上锁了
                    // 查询DB
                    try {
                        skuInfo = skuInfoMapper.selectById(skuId);
                        if (null != skuInfo) {
                            //查询图片
                            skuInfo.setSkuImageList(skuImageMapper.selectList(new QueryWrapper<SkuImage>()
                                    .eq("sku_id", skuId)));
                            //4:保存缓存一份
                            redisTemplate.opsForValue().set(cacheKey,skuInfo,//缓存雪崩
                                    RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300)
                                    , TimeUnit.SECONDS);
                        }else{
                            //缓存的第一大问题 缓存穿透
                            skuInfo = new SkuInfo();//空结果  空对象
                            redisTemplate.opsForValue().set(cacheKey,skuInfo,5, TimeUnit.MINUTES);
                        }
                    } finally {
                        //解锁
                        lock.unlock();
                    }
                }else{
                    //没有上锁
                    //TimeUnit.SECONDS.sleep(2);
                    skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //5:再返回
        return skuInfo;//select id,name, 覆盖索引
    }
*/
    //一二三级分类  ID 名称
    @Override
    @Transactional
    //1:进入切面  spring.xml <bean id="TransactionManageer" tran class="DatasourceTransactionManageer"
    // 1.1  dataSource 连接mysql  tranaction begin
    //2.
    @GmallCache(prefix = "getBaseCategoryView")
    public BaseCategoryView getBaseCategoryView(Long category3Id) {
        //2.1:Mybatis Plus 底层 dataSource  连接Mysql   SQL   select 一二三级分类
        return baseCategoryViewMapper.selectById(category3Id);
    }
    //3. 进入切面  dataSource 连接mysql  commit  rollback

    //单独查询价格  实时价格
    @Override
    public BigDecimal getPrice(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if (null != skuInfo) {
            return skuInfo.getPrice();
        }
        return null;
    }

    //查询销售属性及选中
    @Override
    @GmallCache(prefix = "getSpuSaleAttrListCheckBySku")
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long spuId, Long skuId) {
        return spuSaleAttrMapper.getSpuSaleAttrListCheckBySku(spuId, skuId);
    }

    //查询组合对应的SKUID 为了销售属性选择 跳转 刷新功能
    @Override
    @GmallCache(prefix = "getSkuValueIdsMap")
    public Map getSkuValueIdsMap(Long spuId) {
        List<Map> skuValueIdsMap = skuSaleAttrValueMapper.getSkuValueIdsMap(spuId);
        Map map = new HashMap();
        skuValueIdsMap.forEach(m -> {
            map.put(m.get("values_id"), m.get("sku_id"));
        });
        return map;
    }

    @Override
    public List<BaseCategoryView> getBaseCategoryViewList() {
        return baseCategoryViewMapper.selectList(null);
    }

    @Override
    public BaseTrademark getBaseTrademark(Long tmId) {
        return baseTrademarkMapper.selectById(tmId);
    }

    //查询某一款商品的平台属性集合
    @Override
    public List<SkuAttrValue> getSkuAttrValueAndAttrAndAttrValue(Long skuId) {
        return skuAttrValueMapper.getSkuAttrValueAndAttrAndAttrValue(skuId);
    }

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;
    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;
    @Autowired
    private SpuImageMapper spuImageMapper;
    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;
    @Autowired
    private SkuInfoMapper skuInfoMapper;
    @Autowired
    private SkuImageMapper skuImageMapper;
    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;
    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;
    @Autowired
    private RedisTemplate redisTemplate;
}
